/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.mach.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.common.cache.SysCache;
import org.springblade.common.cache.UserCache;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.mach.entity.DrawingCategory;
import org.springblade.mach.entity.DrawingNumberApplicationDetail;
import org.springblade.mach.entity.EquipmentCategory;
import org.springblade.mach.excel.DrawingNumberApplicationExcel;
import org.springblade.mach.service.IDrawingCategoryService;
import org.springblade.mach.service.IDrawingNumberApplicationDetailService;
import org.springblade.mach.service.IEquipmentCategoryService;
import org.springblade.mach.vo.DrawingNumberApplicationDetailVO;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.mach.entity.DrawingNumberApplication;
import org.springblade.mach.vo.DrawingNumberApplicationVO;
import org.springblade.mach.wrapper.DrawingNumberApplicationWrapper;
import org.springblade.mach.service.IDrawingNumberApplicationService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author LY
 * @since 2021-01-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("data-drawing-number-application/drawingnumberapplication")
@Api(value = "", tags = "接口")
public class DrawingNumberApplicationController extends BladeController {

	private final IDrawingNumberApplicationService drawingNumberApplicationService;
	private final IEquipmentCategoryService equipmentCategoryService;
	private IDrawingCategoryService drawingCategoryService;
	private IDrawingNumberApplicationDetailService drawingNumberApplicationDetailService;


	/**
	 * 查看图号申请得详情表中得记录
	 */
	@GetMapping("/getDrawingApplicationDetailList")
	public R<List<DrawingNumberApplicationDetailVO>> getDrawingApplicationDetailList(@RequestParam("applicationId") Long applicationId) {
		List<DrawingNumberApplicationDetailVO> list = drawingNumberApplicationDetailService.getDetailList(applicationId);
		DrawingNumberApplication application = drawingNumberApplicationService.getById(applicationId);
		list.stream().forEach(drawingNumberApplicationDetailVO -> {
			// 设备分类信息（父类） productParentIdName
			EquipmentCategory parent = equipmentCategoryService.getById(application.getProductParentId());
			drawingNumberApplicationDetailVO.setProductParentIdName(parent.getName());
			// 设备分类信息（字类）
			EquipmentCategory child = equipmentCategoryService.getById(application.getProductChildId());
			drawingNumberApplicationDetailVO.setProductChildIdName(child.getName());
			// 图纸类别分类
			DrawingCategory drawingCategory = drawingCategoryService.getById(application.getDrawingCategory());
			drawingNumberApplicationDetailVO.setDrawingCategoryName(drawingCategory.getName());
			// 申领人
			drawingNumberApplicationDetailVO.setUserAccount(UserCache.getUser(application.getCreateUser()).getAccount());
		});
		return R.data(list);
	}


	/**
	 * @Author zhp
	 * @Description //TODO
	 * @Date 14:16 2021/11/18
	 * @param drawNumber
	 * @return org.springblade.core.tool.api.R<org.springblade.mach.vo.DrawingNumberApplicationDetailVO>
	 * 根据图号获取图纸类型
	*/
	@GetMapping("/getApplicationByNumber")
	public R<DrawingNumberApplicationDetailVO> getApplicationByNumber(@RequestParam("drawNumber") String drawNumber) {
		final BladeUser user = AuthUtil.getUser();
		DrawingNumberApplicationDetailVO list = drawingNumberApplicationDetailService.getApplicationByNumber(drawNumber,user.getUserId());
		return R.data(list);
	}


	/**
	 * 导出图号申请中得数据
	 */
	@GetMapping("export-drawing-number-application")
	public void exportDrawingNumberExcel(@RequestParam Map<String, Object> drawingNumberApplication, HttpServletResponse response) {
		QueryWrapper<DrawingNumberApplication> queryWrapper = Condition.getQueryWrapper(drawingNumberApplication, DrawingNumberApplication.class);
		queryWrapper.lambda().eq(DrawingNumberApplication::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		final boolean administrator = AuthUtil.isAdministrator();
		if (!administrator) {
			final BladeUser user = AuthUtil.getUser();
			queryWrapper.lambda().eq(DrawingNumberApplication::getCreateUser, user.getUserId());
		}
		List<DrawingNumberApplicationExcel> drawingNumberApplicationExcels = drawingNumberApplicationService.exportExcel(queryWrapper);
		drawingNumberApplicationExcels.stream().forEach(drawingNumberApplicationExcel -> {
			// 设备分类信息（父类）
			EquipmentCategory parent = equipmentCategoryService.getById(drawingNumberApplicationExcel.getProductParentId());
			drawingNumberApplicationExcel.setProductParentIdName(parent.getName());
			// 设备分类信息（字类）
			EquipmentCategory child = equipmentCategoryService.getById(drawingNumberApplicationExcel.getProductChildId());
			drawingNumberApplicationExcel.setProductChildIdName(child.getName());
			// 图纸类别分类
			DrawingCategory drawingCategory = drawingCategoryService.getById(drawingNumberApplicationExcel.getDrawingCategory());
			drawingNumberApplicationExcel.setDrawingCategoryName(drawingCategory.getName());
			// 申请人信息
			User createUser = UserCache.getUser(drawingNumberApplicationExcel.getCreateUser());
			drawingNumberApplicationExcel.setUserAccount(createUser.getName());
			// 申请部门
			List<String> deptName = SysCache.getDeptNames(String.valueOf(drawingNumberApplicationExcel.getCreateDept()));
			drawingNumberApplicationExcel.setDeptName(Func.join(deptName));
		});
		ExcelUtil.export(response, "图号申领数据" + DateUtil.time(), "图号申领数据表",
			drawingNumberApplicationExcels, DrawingNumberApplicationExcel.class);
	}

	/**
	 * 图号申请表单的内容回显
	 */
	@GetMapping("/getDrawingPersonInfo")
	public R<UserVO> getDrawingPersonInfo(BladeUser bladeUser) {
		User user = UserCache.getUser(bladeUser.getUserId());
		return R.data(UserWrapper.build().entityVO(user));
	}

	/**
	 * 寻找设备分类中所有的父节点的列表
	 */
	@GetMapping("/getEquipmentCategoryParentNode")
	public R<List<EquipmentCategory>> getCategpryParent() {
		List<EquipmentCategory> parentNode = equipmentCategoryService.getParentNode();
		return R.data(equipmentCategoryService.getParentNode());
	}

	/**
	 * 寻找父节点设备下，对应的总结点的列表信息
	 */
	@GetMapping("/getChildNodeByParentId")
	public R<List<EquipmentCategory>> getChildNodeByParentId(Long parentId) {
		return R.data(equipmentCategoryService.getChildNode(parentId));
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入drawingNumberApplication")
	public R<DrawingNumberApplicationVO> detail(DrawingNumberApplication drawingNumberApplication) {
		DrawingNumberApplication detail = drawingNumberApplicationService.getOne(Condition.getQueryWrapper(drawingNumberApplication));
		DrawingNumberApplicationVO drawingNumberApplicationVO = DrawingNumberApplicationWrapper.build().entityVO(detail);
		// 设备分类信息（父类）
		EquipmentCategory parent = equipmentCategoryService.getById(drawingNumberApplicationVO.getProductParentId());
		drawingNumberApplicationVO.setProductParentIdName(parent.getName());
		// 设备分类信息（字类）
		EquipmentCategory child = equipmentCategoryService.getById(drawingNumberApplicationVO.getProductChildId());
		drawingNumberApplicationVO.setProductChildIdName(child.getName());
		// 图纸类别分类
		DrawingCategory drawingCategory = drawingCategoryService.getById(drawingNumberApplicationVO.getDrawingCategory());
		drawingNumberApplicationVO.setDrawingCategoryName(drawingCategory.getName());
		return R.data(drawingNumberApplicationVO);
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入drawingNumberApplication")
	public R<IPage<DrawingNumberApplicationVO>> list(@RequestParam Map<String, Object> drawingNumberApplication, Query query) {
		final BladeUser user = AuthUtil.getUser();
		IPage<DrawingNumberApplication> pages = drawingNumberApplicationService.page(Condition.getPage(query),
			Condition.getQueryWrapper(drawingNumberApplication, DrawingNumberApplication.class).lambda().eq(BaseEntity::getCreateUser, user.getUserId())
				.orderByDesc(DrawingNumberApplication::getCreateTime));
		IPage<DrawingNumberApplicationVO> pageList = DrawingNumberApplicationWrapper.build().pageVO(pages);
		pageList.getRecords().stream().forEach(drawingNumberApplicationVO -> {
			// 设备分类信息（父类）
			EquipmentCategory parent = equipmentCategoryService.getById(drawingNumberApplicationVO.getProductParentId());
			drawingNumberApplicationVO.setProductParentIdName(parent.getName());
			// 设备分类信息（字类）
			EquipmentCategory child = equipmentCategoryService.getById(drawingNumberApplicationVO.getProductChildId());
			drawingNumberApplicationVO.setProductChildIdName(child.getName());
			// 图纸类别分类
			DrawingCategory drawingCategory = drawingCategoryService.getById(drawingNumberApplicationVO.getDrawingCategory());
			drawingNumberApplicationVO.setDrawingCategoryName(drawingCategory.getName());
		});
		return R.data(pageList);
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入drawingNumberApplication")
	public R<IPage<DrawingNumberApplicationVO>> page(DrawingNumberApplicationVO drawingNumberApplication, Query query) {
		IPage<DrawingNumberApplicationVO> pages = drawingNumberApplicationService.selectDrawingNumberApplicationPage(Condition.getPage(query), drawingNumberApplication);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入drawingNumberApplication")
	public R save(@Valid @RequestBody DrawingNumberApplication drawingNumberApplication) {
		return R.status(drawingNumberApplicationService.saveDrawingNumberApplicationAndDetail(drawingNumberApplication));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入drawingNumberApplication")
	public R update(@Valid @RequestBody DrawingNumberApplication drawingNumberApplication) {
		return R.status(drawingNumberApplicationService.updateById(drawingNumberApplication));
	}

	/**
	 * 修改图号申请记录
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入drawingNumberApplication")
	public R submit(@Valid @RequestBody DrawingNumberApplication drawingNumberApplication) {

		return R.status(drawingNumberApplicationService.saveOrUpdate(drawingNumberApplication));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(drawingNumberApplicationService.deleteLogic(Func.toLongList(ids)));
	}


}
